package com.zone.lib.download.db;

import com.zone.lib.download.db.entity.Download;
import com.zone.lib.download.db.gen.DownloadDao;
import com.zone.lib.download.utils.BeanUtils;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

/**
 * @Author: pkqlqx
 * @CreateDate: 2021/12/7 16:58
 * @Description: 初始化、存放及获取DaoUtils
 */
public class DownloadDaoUtilsStore {
    private volatile static DownloadDaoUtilsStore instance = new DownloadDaoUtilsStore();
    private DownloadDaoUtils<Download> downloadDownloadDaoUtils;

    public static DownloadDaoUtilsStore getInstance() {
        return instance;
    }

    private DownloadDaoUtilsStore() {
        DownloadDaoManager mManager = DownloadDaoManager.getInstance();
        DownloadDao downloadDao = mManager.getDaoSession().getDownloadDao();
        downloadDownloadDaoUtils = new DownloadDaoUtils<>(Download.class, downloadDao);
    }

    public DownloadDaoUtils<Download> getDownloadAppDaoUtils() {
        return downloadDownloadDaoUtils;
    }

    public Download getDownloadByCode(String code){
        if (StringUtils.isEmpty(code)){
            return null;
        }
        List<Download> downloadList = downloadDownloadDaoUtils.queryByQueryBuilder(DownloadDao.Properties.Code.eq(code));
        return ObjectUtils.isNotEmpty(downloadList)?downloadList.get(0):null;
    }

    public boolean deleteByCode(String code){
        Download download = getDownloadByCode(code);
        if (download != null){
            return downloadDownloadDaoUtils.delete(download);
        }
        return false;
    }

    public boolean update(Download download){
        Download old = getDownloadByCode(download.getCode());
        if (old != null){
            try {
                BeanUtils.copyProperties(download, old);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return downloadDownloadDaoUtils.update(old);
        }
        return false;
    }

}